package com.alnex.mongo.controller;

import cn.hutool.core.util.StrUtil;
import com.alnex.mongo.entity.Test;
import com.alnex.mongo.entity.User;
import com.alnex.mongo.res.UserRequest;
import com.alnex.mongo.service.TestService;
import com.alnex.mongo.service.Uservervice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @author admin
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    Uservervice uservervice;

    @Autowired
    TestService testService;

    @Autowired
    MongoOperations mongoOperations;

    @PostMapping("/save")
    public Object saveUser(@RequestBody User user) {
        uservervice.save(user);
        return "sucess";
    }

    @GetMapping("/find/user/{id}")
    public Object findTest(@PathVariable String id) {
        return uservervice.findById(id, new User());
    }

    @PostMapping("/find/all")
    public Object findAllTest(@RequestBody UserRequest request) {
        return uservervice.findAll(new User(), request);
    }

    @DeleteMapping("/delete/user/{id}")
    public void deleteTest(@PathVariable String id) {
        uservervice.deleteById(id, new User());
    }

    @GetMapping("/find/test/{id]")
    public Object saveTest(@PathVariable String id) {
        return testService.findById(id, new Test());
    }

    @PostMapping("/find/test/all")
    public Object saveTest(@RequestBody Test test) {
        Query query = new Query();
        Criteria criteria = new Criteria();

        String title = test.getTitle();
        String by = test.getBy();
        String likes = test.getLikes();
        String description = test.getDescription();
        List<String> tags = test.getTags();

        if (StrUtil.isNotBlank(title)){
            criteria.and("title").is(title);
        }
        if (StrUtil.isNotBlank(by)){
            criteria.and("by").is(by);
        }
        if (StrUtil.isNotBlank(likes)) {
            criteria.and("likes").is(likes);
        }
        if (StrUtil.isNotBlank(description)) {
            Pattern pattern = Pattern.compile("^.*" + description + ".*$", Pattern.CASE_INSENSITIVE);
            criteria.and("description").regex(pattern);
        }
        if (tags.size() > 0){
            criteria.and("tags").in(tags);
        }
        query.addCriteria(criteria);

        return mongoOperations.find(query, Test.class);
    }
}